﻿using System;
using System.Diagnostics;
using System.Web;
using System.Web.Security;

namespace Library
{
    public class AuthenticateUtility
    {
        public const string ADMIN_PREFIX = "moduleAdministrator_";

        public static string GetUserEmail()
        {
            return HttpContext.Current.User.Identity.Name.Replace(ADMIN_PREFIX, string.Empty);
        }

        public static bool IsAuthenticated()
        {
            HttpContext context = HttpContext.Current;
            return
            context.User.Identity.IsAuthenticated && (context.User.Identity.Name.IndexOf(ADMIN_PREFIX) != -1);
        }
        public static void LoginUser(string _email, bool _rememberAccount)
        {
            LogoutUser();
            FormsAuthentication.Initialize();
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, ADMIN_PREFIX + _email, DateTime.Now, DateTime.Now.AddMinutes(45), _rememberAccount, "", FormsAuthentication.FormsCookiePath);
            Trace.Write(FormsAuthentication.FormsCookiePath + FormsAuthentication.FormsCookieName);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
            HttpContext.Current.Response.SetCookie(cookie);
        }

        public static void LogoutUser()
        {
            HttpContext.Current.Items.Remove("ADMIN_INFO");
            HttpContext.Current.Session.Abandon();
            FormsAuthentication.SignOut();
        }
    }
}
